const express = require('express')
const routers = express.Router()   // 创建模块化

const readFile = require('./readFile')

routers.get('/box_link', (req, res) => {
  readFile(['box', 'link']).then(data => {
    const resData = integrate(data)
    res.send(resData)
  })
}) 

function integrate(data) {
  const [box, link] = data
  const boxData = sortFn(box)
  const linkData = sortFn(link)
  linkData.forEach((item) => {
    const {box_id} = item
    const boxObj = boxData.find(itemB => itemB.id === box_id)
    if(!boxObj?.children) { boxObj.children = [] }
    boxObj.children.push(item)
  })
  return boxData
}

function sortFn(agrData) {
  const data = JSON.parse(agrData)
  data.sort((a, b) =>  a.item_order - b.item_order)
  return data
  
}

module.exports = routers